package com.adv.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
	private JsonUtil() {
	}

	public static ObjectMapper om;

	static {
		om = new ObjectMapper();
		// om.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY,
		// false);
	}

	/** 
	 * 类对象转换成JSON字符串 
	 *  
	 * @param obj 
	 * @return 
	 */
	public static String toJSON(Object obj) {
		try {
			return om.writeValueAsString(obj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/** 
	 * JSON字符串转换成类对象 
	 *  
	 * @param <T> 
	 * @param json 
	 * @param t 
	 * @return 
	 */
	public static <T> T toBean(String json, Class<T> t) {
		try {
			return om.readValue(json, t);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/** 
	 * JSON字符串转换成Map对象 
	 */
	public static Map<String, Object> toMap(String json) {
		try {
			return om.readValue(json, new TypeReference<Map<String, Object>>() {
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/** 
	 * JSON转换为集合 
	 */
	public static List<Map<String, List<String>>> toList(String json) {
		try {
			return om.readValue(json, new TypeReference<List<Map<String, List<String>>>>() {
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		List<Map<String, List<String>>> list = new ArrayList<Map<String, List<String>>>();
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		map.put("bbb", new ArrayList<String>());
		map.get("bbb").add("hello");
		map.put("aaa", new ArrayList<String>());
		list.add(map);
		String json = toJSON(list);
		System.out.println(json);
		list = toList(json);
		System.out.println(list.get(0).size());

	}
}
